package com.ys.service.purchase.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.flow.YspModel;
import com.ys.entity.purchase.*;
import com.ys.entity.storage.TccFbaPlan;
import com.ys.entity.sys.*;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.enume.purchase.TcgPurchasePlanGoodsEnum;
import com.ys.mapper.product.ProductMapper;
import com.ys.mapper.purchase.TcgPurchaseByOrderMapper;
import com.ys.mapper.purchase.TcgPurchaseByPlanMapper;
import com.ys.mapper.purchase.TcgPurchaseByPlanSonMapper;
import com.ys.mapper.purchase.TcgPurchasePlanGoodsMapper;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseByOrderService;
import com.ys.service.purchase.TcgPurchaseByPlanService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 采购计划单
 */
@Service("tcgPurchaseByPlanService")
public class TcgPurchaseByPlanServiceImpl implements TcgPurchaseByPlanService {
	private static final Logger logger = LoggerFactory.getLogger(TcgPurchaseByPlanServiceImpl.class);

	@Autowired
	private TcgPurchaseByPlanMapper tcgPurchaseByPlanMapper;

	@Autowired
	private TcgPurchasePlanGoodsMapper tcgPurchasePlanGoodsMapper;

	@Autowired
	private TcgPurchaseByPlanSonMapper tcgPurchaseByPlanSonMapper;

	@Autowired
	private TcgPurchaseByOrderMapper tcgPurchaseByOrderMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

	@Autowired
	private TcgPurchaseByOrderService tcgPurchaseOrderService;
	@Autowired
	private CommonApiService<TccFbaPlan> commonApiService;

	private final Long GRID = 63L;

    private final ReentrantLock lock = new ReentrantLock();//同步锁

	/**
	 * 新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("新增传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcgPurchaseByPlan entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchaseByPlan.class);
		entity.setStatus(1);//状态
		entity.setEffectStock(0);//审批状态

        try {
            lock.lock(); // 加锁
            int bidIsAdd = new TcgPurchaseByPlan().setBid(entity.getBid()).count();
            if(bidIsAdd>0){
                String bid = commonApiService.getCommonNextBid(menuId);
                entity.setBid(bid);
            }
            lock.unlock(); // 释放锁
        }finally {
            try {
                lock.unlock(); // 确保释放锁
            }catch (Exception e){}
        }


		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
		if(tsUserChange!=null){
			entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			return R.error("未查询到制单人信息！");
		}

		//保存列表信息
		R saveItemRes = saveItem(params,entity,true);
		if(saveItemRes.getCode()==1){
			return saveItemRes;
		}

		//新增
		tcgPurchaseByPlanMapper.insert(entity);

		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, entity.getBid(), createUserId);
		}
		//return R.ok(EditDto.closeAndReload());
		return R.ok(AddDto.gotoEdit("/web/purchase/tcgPurchaseByPlan/toEdit?bid=" + entity.getBid()));
	}


	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcgPurchaseByPlan entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchaseByPlan.class);
		// 验证状态
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst == null) {
			return R.error("审批数据不存在，无法编辑");
		} else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("已流转，无法编辑");
		}

		//保存列表信息
		R saveItemRes = saveItem(params,entity,false);
		if(saveItemRes.getCode()==1){
			return saveItemRes;
		}
		tcgPurchaseByPlanMapper.update(entity);
		return R.ok();
	}


	//保存子列表信息
	public R saveItem(Map<String, Object> params, TcgPurchaseByPlan entity,boolean isAdd) throws Exception{
		//保存列表信息
		List<Map<String, Object>> subDataList = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			CheckByGrid checkByGrid = checkParamsByGrid(subData,GRID,params);
			if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
				return R.error(checkByGrid.getErrMsg());
			}
			subDataList = checkByGrid.getSubDataList();
		}else {
			return R.error("列表信息为空！");
		}

		//删除母件表信息
		productMapper.deleteTcgPurchaseByPlanGoodsByPbid(entity.getBid());
		//删除子件表信息
		productMapper.deleteTcgPurchaseByPlanSonByPbid(entity.getBid());

		if(entity.getIsJgSub()==0){
			List<Map<String, Object>> subDataListByNew = new ArrayList<>();
			for (Map<String, Object> item:subDataList) {
				item.put("jgSl",0);
				item.put("subTotalAmount",item.get("purchaseAmount"));
				subDataListByNew.add(item);
			}
			subDataList = subDataListByNew;
		}

		//剔除：子件采购总数为0的数据，若母件对应子件都为0，则母件信息也剔除
		subDataList = subDataList.stream().filter(item->{
			boolean isNotDel = true;
			if(checkUtil.isNullByObject(item.get("subTotalAmount")) || checkUtil.isZero(item.get("subTotalAmount").toString())){//子件总数
				isNotDel = false;
			}
			return isNotDel;
		}).collect(Collectors.toList());


		//再新增
		//新增母件表信息
		//去重
		Map<String, List<Map<String, Object>>> groupsByCode = subDataList.stream().collect(Collectors.groupingBy(e->e.get("spBm").toString()));
		List<Map<String, Object>> codeList = new ArrayList<>();
		//遍历，填入去重的母件商品信息
		groupsByCode.forEach((k, v) -> {
			Map<String, Object> info = new HashMap<>();
			info.put("spBm",v.get(0).get("spBm"));
			info.put("spAmount",v.get(0).get("spAmount"));
			info.put("stockAmount",v.get(0).get("stockAmount"));
			info.put("orderStatus",checkUtil.isNotNullByObject(v.get(0).get("orderStatus"))?v.get(0).get("orderStatus"):TcgPurchasePlanGoodsEnum.OrderStatus.ORDER_NO.value);
			codeList.add(info);
		});

		List<TcgPurchasePlanGoods> goodsList = new ArrayList<>();
		for (int i = 0; i < codeList.size(); i++) {
			TcgPurchasePlanGoods goodsEntity = JSON.parseObject(JSON.toJSONString(codeList.get(i)), TcgPurchasePlanGoods.class);
			goodsEntity.setPbid(entity.getBid());
			goodsEntity.setStatus(1);
			goodsEntity.setStoreIntegrity(0);//入库完整性
			//goodsEntity.setOrderStatus(TcgPurchasePlanGoodsEnum.OrderStatus.ORDER_NO.value);
			tcgPurchasePlanGoodsMapper.insert(goodsEntity);
			goodsList.add(goodsEntity);
		}

		//新增子件信息
		for (int i = 0; i < subDataList.size(); i++) {
			Map<String, Object> item = subDataList.get(i);
			String spBm = item.get("spBm").toString();
			BigDecimal subTotalAmount = new BigDecimal(item.get("subTotalAmount").toString()).setScale(0, BigDecimal.ROUND_DOWN);
			item.put("subTotalAmount",subTotalAmount);
			BigDecimal jgSl = new BigDecimal(item.get("jgSl").toString()).setScale(0, BigDecimal.ROUND_DOWN);
			item.put("jgSl",jgSl);
			BigDecimal purchaseAmount = new BigDecimal(item.get("purchaseAmount").toString()).setScale(0, BigDecimal.ROUND_DOWN);
			item.put("purchaseAmount",purchaseAmount);

			TcgPurchaseByPlanSon itemInfo = JSON.parseObject(JSON.toJSONString(item), TcgPurchaseByPlanSon.class);
			itemInfo.setStatus(1);
			itemInfo.setPbid(entity.getBid());
			for(TcgPurchasePlanGoods goodItem:goodsList){
				if(spBm.equals(goodItem.getSpBm())){
					itemInfo.setPid(goodItem.getId());
				}
			}
			itemInfo.setStoreAmount(BigDecimal.ZERO);//入库数量初始默认0



			//新增
			tcgPurchaseByPlanSonMapper.insert(itemInfo);
		}

		/*
		//冻结资金
		List<Map<String,Object>> itemList = getItemListByBid(entity.getBid());
		BigDecimal subTotalPrice = BigDecimal.ZERO;
		//遍历详情信息
		for (Map<String,Object> item : itemList){
			subTotalPrice = subTotalPrice.add(new BigDecimal(item.get("subTotalPrice").toString()));

		}
		//获取公司编码
		String vGsBm = entity.getVgsbm();
		//根据公司编码获取对应的实时资金表信息
		TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
		//获取对应的实时资金信息
		BigDecimal amountAble = account.getFJe().add(account.getFFzEd()).subtract(account.getFDjJe());
		//判断金额是否大于公司的实时资金
		if (amountAble.compareTo(subTotalPrice) < 0) {
			return R.error("【" + vGsBm + "】账户可用余额不足");
		}
		if(!isAdd){
			//解冻
			tcwAccountCountForCompanyService.thaw(vGsBm, subTotalPrice);
		}
		//冻结
		tcwAccountCountForCompanyService.frozen(vGsBm, subTotalPrice);

		 */
		return R.ok();
	}


	//删除
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R del(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		TcgPurchaseByPlan entity = new TcgPurchaseByPlan().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		if (!tsUserChange.getUserId().equals(loginUserId) && !"admin".equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
			BigDecimal subTotalPrice = BigDecimal.ZERO;
			//获取
			List<Map<String,Object>> itemList = getItemSearchByComm().setPbid(entity.getBid()).queryMap();
			//遍历详情信息
			for (Map<String,Object> item : itemList){
				subTotalPrice = subTotalPrice.add(new BigDecimal(item.get("subTotalPrice").toString()));
			}
			//解冻
			tcwAccountCountForCompanyService.thaw(entity.getVgsbm(), subTotalPrice,
					TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByPlan.value,
					entity.getId(),
					entity.getBid(),
					null);
		}
		
		//删除
		tcgPurchaseByPlanMapper.deleteTrue(id);
		//删除母件表信息
		productMapper.deleteTcgPurchaseByPlanGoodsByPbid(entity.getBid());
		//删除子件表信息
		productMapper.deleteTcgPurchaseByPlanSonByPbid(entity.getBid());
		//删除流程
		yspTaskService.flowDelete(entity.getBid(), loginUserId);

		return R.ok();
	}



	/**
	 * 流转通过
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowPass(Long id,String userId) throws Exception {
		//获取单据信息
		TcgPurchaseByPlan entity = new TcgPurchaseByPlan().setId(id).queryFirst();
		if (entity == null) {
			return R.error("该单据不存在,请核实后再操作!");
		}
		List<Map<String,Object>> itemList = getItemListByBid(entity.getBid());
		BigDecimal subTotalPrice = BigDecimal.ZERO;
		//遍历详情信息
		for (Map<String,Object> item : itemList){
			subTotalPrice = subTotalPrice.add(new BigDecimal(item.get("subTotalPrice").toString()));
		}
		//获取公司编码
		String vGsBm = entity.getVgsbm();
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		// 若流程是初始化状态，需要验证账户金额
		if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {

			//根据公司编码获取对应的实时资金表信息
			TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
			//获取对应的实时资金信息
			BigDecimal amountAble = account.getFJe().add(account.getFFzEd()).subtract(account.getFDjJe());
			//判断金额是否大于公司的实时资金
			if (amountAble.compareTo(subTotalPrice) < 0) {
				return R.error("【" + vGsBm + "】账户可用余额不足");
			}
		}

		Flow f = yspTaskService.flowPass(entity.getBid(),userId);

		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			// 若是制单流转，冻结账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				//冻结
				tcwAccountCountForCompanyService.frozen(vGsBm, subTotalPrice,
						TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByPlan.value,
						entity.getId(),
						entity.getBid(),
						null);
			}
			if (f.getState() == Flow.State.FINISH.value) {
				return flowFinish(entity);
			}
			return R.ok();
		}
	}

	/**
	 * 流转结束
	 */
	public R flowFinish(TcgPurchaseByPlan entity) throws Exception {

		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return R.error("审批状态有误，无法流转");
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);


		//修改信息
		tcgPurchaseByPlanMapper.update(entity);
		return R.ok();

	}

	//流转驳回
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowRefuse(String bid, String reason,String userId) throws Exception{
		R r = yspTaskService.flowRefuse(bid, reason, userId);

		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				TcgPurchaseByPlan entity = new TcgPurchaseByPlan().setBid(bid).queryFirst();
				List<Map<String,Object>> itemList = getItemListByBid(entity.getBid());

				BigDecimal subTotalPrice = BigDecimal.ZERO;
				//遍历详情信息
				for (Map<String,Object> item : itemList){
					subTotalPrice = subTotalPrice.add(new BigDecimal(item.get("subTotalPrice").toString()));
				}
				//获取公司编码
				String vGsBm = entity.getVgsbm();
				//解冻
				tcwAccountCountForCompanyService.thaw(vGsBm, subTotalPrice,
						TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByPlan.value,
						entity.getId(),
						entity.getBid(),
						null);
			}
		}
		return r;
	}


	//流转退回
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowInit(String bid, String reason,String userId) throws Exception{
		R r = yspTaskService.flowInit(bid, reason, userId);
		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				TcgPurchaseByPlan entity = new TcgPurchaseByPlan().setBid(bid).queryFirst();
				List<Map<String,Object>> itemList = getItemListByBid(entity.getBid());

				BigDecimal subTotalPrice = BigDecimal.ZERO;
				//遍历详情信息
				for (Map<String,Object> item : itemList){
					subTotalPrice = subTotalPrice.add(new BigDecimal(item.get("subTotalPrice").toString()));
				}
				//获取公司编码
				String vGsBm = entity.getVgsbm();
				//解冻
				tcwAccountCountForCompanyService.thaw(vGsBm, subTotalPrice,
						TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByPlan.value,
						entity.getId(),
						entity.getBid(),
						null);
			}
		}
		return r;
	}



	//根据主表bid获取子表信息
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public List<Map<String,Object>> getItemListByBid(String bid) throws Exception{
		List<Map<String,Object>> itemList = getItemSearchByComm()
				.setPbid(bid)
				.setOrderby("A.SpBm,F.SubCode")
				.queryMap();

		return itemList;
	}

	//获取子表信息的通用查询语句
	public TcgPurchasePlanGoods getItemSearchByComm()throws Exception{
		return new TcgPurchasePlanGoods()

				//.addLeftJoin("TCG_PurchasePlanGoods B ON B.Pbid = A.Bid ")//计划单母件信息表
				//.addField("B.SpBm AS spBm")//母件商品编码
				//.addField("B.OrderStatus AS orderStatus")//订单状态
				//.addField("B.SpAmount AS spAmount")//采购数量

				.addLeftJoin("TP_ProductActive C ON C.Code = A.SpBm ")//商品母件信息表
				.addField("C.Name AS spName")//商品名称




				.addLeftJoin("THR_OperateCompanyApply U ON  U.VGsBm = C.VgsBm")
		.addField("U.Vgsjc AS vgsjcBySub")
		.addField("U.Vgsbm AS vgsbmBySub")

				.addLeftJoin("TCG_PurchaseByPlanSon F ON F.Pid = A.Id ")//计划单子件信息表
				.addField("F.Id AS purchasePlanSonId")//id
				.addField("F.SubCode AS subCode")//子件编码
				.addField("F.SubAmount AS subAmount")//子件数量
				.addField("F.PurchaseAmount AS purchaseAmount")//计划采购数量
				.addField("F.JgSl AS jgSl")//子件加购数量
				.addField("F.Bprice AS bprice")//子件预估单价
				.addField("F.SubStockAmount AS subStockAmount")//子件库存数量
				.addField("F.SubTotalPrice AS subTotalPrice")//子件预估总价
				.addField("F.SubTotalAmount AS subTotalAmount")//子件总数
				.addField("F.SubName AS subName")//子件名称
				.addField("F.SubRemark AS subRemark")//子件备注

				.addLeftJoin("TP_ProductBasisComponent G ON G.Code = F.SubCode ")//商品子件信息表
				.addField("G.LinkIn AS linkIn")//采购链接

		;
	}


	//获取生成采购订单需要的子表信息
	@Override
	public List<Map<String,Object>> getItemListToOrder(Long goodsId,String planBid) throws Exception{
		List<Map<String,Object>> itemList = getItemSearchByComm()

				.addLeftJoin("TCG_Distribution D ON D.Scode = F.SubCode")//1688铺货单信息表
				.addField("D.GoodsId AS goodsId")//商品ID
				.addField("D.SupplierId AS supplierId")//供应商ID
				.addField("D.Aname AS aname")//1688账号
				.addField("D.SkuId AS skuId")//SKUID
				.addField("D.Name AS tradeName")//商品标题
				.addField("D.SpecId AS specId")//SpecId
				.addField("D.SkupRoperty AS skupRoperty")//SKU属性
				.addField("D.SkuCode AS skuCode")//SKU编码
				.setOrderStatus(TcgPurchasePlanGoodsEnum.OrderStatus.ORDER_NO.value)
				.setPbid(planBid)
				.setId(goodsId)
				.queryMap();

		return itemList;
	}



	/**
	 * 生成订单
	 */
	@Override
	public R produceOrder(Map<String, Object> params) throws Exception {
        long goodsId = Long.parseLong(params.get("goodsId").toString());

        TcgPurchasePlanGoods tcgPurchasePlanGoods = new TcgPurchasePlanGoods().setId(goodsId).queryFirst();
        if(tcgPurchasePlanGoods==null){
            return R.error("未查询到对应的计划单信息");
        }
		TcgPurchaseByPlan tcgPurchasePlan = new TcgPurchaseByPlan().setBid(tcgPurchasePlanGoods.getPbid()).queryFirst();
        if(tcgPurchasePlan==null){
            return R.error("未查询到对应的计划单信息");
        }
        if(tcgPurchasePlan.getEffectStock() != 1){
            return R.error("该计划单未审批流转完成");
        }
        if(tcgPurchasePlanGoods.getOrderStatus()!=0){
            return R.error("该计划单处于："+TcgPurchasePlanGoodsEnum.OrderStatus.getName(tcgPurchasePlanGoods.getOrderStatus())+"状态，不可再生成采购订单");
        }

		List<Map<String,Object>> itemList = getItemSearchByComm().setId(goodsId).queryMap();
        if(itemList==null || itemList.size()<=0){
			return R.error("未查询到对应的计划单子件表信息");
		}

		String backMsg = "";
        for(Map<String,Object> item : itemList){
			int is1688 = new TcgDistribution().setScode(item.get("subCode").toString()).count();
			if(is1688<=0){
				backMsg += "子件："+item.get("subCode").toString()+"必须先1688铺货；";
			}
		}
        if(!"".equals(backMsg)){
			return R.error(backMsg);
		}

        //生成采购订单操作
		tcgPurchaseOrderService.addByPlan(goodsId,tcgPurchasePlan.getBid());



		return R.ok();
	}




	/**
	 * 确认取消订单
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R cancel(Map<String, Object> params) throws Exception {
		long goodsId = Long.parseLong(params.get("goodsId").toString());
		TcgPurchasePlanGoods tcgPurchasePlanGoods = new TcgPurchasePlanGoods().setId(goodsId).queryFirst();
		if(tcgPurchasePlanGoods==null){
			return R.error("未查询到对应的计划单信息");
		}
		TcgPurchaseByPlan tcgPurchasePlan = new TcgPurchaseByPlan().setBid(tcgPurchasePlanGoods.getPbid()).queryFirst();
		if(tcgPurchasePlan==null){
			return R.error("未查询到对应的计划单信息");
		}
		if(tcgPurchasePlan.getEffectStock() != 1){
			return R.error("该计划单未审批流转完成，无法取消");
		}
		if(tcgPurchasePlanGoods.getOrderStatus()!=0 && tcgPurchasePlanGoods.getOrderStatus()!=2){
			return R.error("该计划单处于："+TcgPurchasePlanGoodsEnum.OrderStatus.getName(tcgPurchasePlanGoods.getOrderStatus())+"状态，不可取消");
		}
		List<TcgPurchaseByOrder> orderList = new TcgPurchaseByOrder().setPurchasePlanGoodsId(goodsId).queryList();
		if(orderList!=null && orderList.size()>0){
			for(TcgPurchaseByOrder tcgPurchaseByOrder:orderList){
				if(!tcgPurchaseByOrder.getOrderStatus().equals(TcgPurchaseByOrderEnum.OrderStatus.CANCEL_YB_1688.value)){
					return R.error("采购订单："+tcgPurchaseByOrder.getBid()+"还未取消，无法进行计划取消；");
				}
			}
		}


		//获取
		List<Map<String,Object>> itemList = getItemSearchByComm().setId(goodsId).queryMap();

		BigDecimal subTotalPrice = BigDecimal.ZERO;
		//遍历详情信息
		for (Map<String,Object> item : itemList){
			subTotalPrice = subTotalPrice.add(new BigDecimal(item.get("subTotalPrice").toString()));

		}


		//获取公司编码
		String vGsBm = tcgPurchasePlan.getVgsbm();

		//解冻
		tcwAccountCountForCompanyService.thaw(vGsBm, subTotalPrice,
				TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByPlan.value,
				tcgPurchasePlan.getId(),
				tcgPurchasePlan.getBid(),
				null);

		//修改计划单状态
		TcgPurchasePlanGoods entity = new TcgPurchasePlanGoods().setId(goodsId).queryFirst();
		entity.setOrderStatus(TcgPurchasePlanGoodsEnum.OrderStatus.ORDER_CANCEL.value);
		tcgPurchasePlanGoodsMapper.update(entity);

		//同步修改采购订单状态
		List<TcgPurchaseByOrder> orderEntity = new TcgPurchaseByOrder()
				.setPlanBid(tcgPurchasePlan.getBid())
				.setPurchasePlanGoodsId(goodsId)
				.setStatus(1)
				.setOperateStatus(0)
				.queryList();
		if(orderEntity!=null && orderEntity.size()>0){
			for(TcgPurchaseByOrder item:orderEntity){
				item.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PLAN_CANCEL.value);
				tcgPurchaseByOrderMapper.update(item);
			}
		}

		return R.ok();
	}



	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCG_PurchaseByPlan",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		if(checkUtil.isNullByObject(params.get("vgsSh"))){//运营公司税号
			backMsg = "运营公司税号不能为空";
		}
		return backMsg;
	}


	/**
	 * 子表参数验证
	 */
	public CheckByGrid checkParamsByGrid(JSONArray subDataArray, Long gridId,Map<String, Object> params) throws Exception {
		CheckByGrid checkByGrid = new CheckByGrid();
		//获取pc字段数据
		List<YsGridCol> listField = new YsGridCol()
				.setGridId(gridId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		String backMsg = "";
		List<Map<String, Object>> subDataList = new ArrayList<>();

		if(subDataArray!=null && subDataArray.size()>0){
			for (int i = 0; i < subDataArray.size(); i++) {
				JSONObject jsonObject = subDataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				subDataList.add(paramsNewByRecord);
			}
			BigDecimal subTotalPrice = BigDecimal.ZERO;
			//验证
			for(int i = 0;i<subDataList.size();i++){
				String backMsgByRow = "";
				Map<String, Object> subData = subDataList.get(i);
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsgByRow += checkUtil.checkTableColLengthAndDataTypeByGrid(
						"TCG_PurchaseByPlanSon",
						listField,
						subData,
						ysColItem->
								ysColItem.getCode().equals("spBm")//商品编码
										|| ysColItem.getCode().equals("subCode")//子件编码
										|| ysColItem.getCode().equals("subAmount")//子件数量
										|| ysColItem.getCode().equals("bprice")//子件预估单价

				);

                if(checkUtil.isNotNullByObject(subData.get("subCode"))){//子件编码，必须是1688已铺货才可保存
					int is1688 = new TcgDistribution().setScode(subData.get("subCode").toString()).count();
					if(is1688<=0){
						backMsgByRow += "子件："+subData.get("subCode").toString()+"必须先1688铺货；";
					}
                }
				if(checkUtil.isNotNullByObject(subData.get("bprice"))){//子件预估单价
					if(new BigDecimal(subData.get("bprice").toString()).compareTo(BigDecimal.ZERO)<=0){
						backMsgByRow += "子件预估单价必须大于0；";
					}
				}

				if(checkUtil.isNotNullByObject(subData.get("jgSl"))){//加购数量不为空时，必须是整数
					if(!checkUtil.isZero(subData.get("jgSl").toString()) && !checkUtil.isPositiveInteger(subData.get("jgSl").toString())){
						backMsgByRow += "加购数量必须为正整数；";
					}
				}

				if(checkUtil.isNotNullByObject(subData.get("spAmount"))){//采购数量不为空时，必须是整数
					if(!checkUtil.isZero(subData.get("spAmount").toString()) && !checkUtil.isPositiveInteger(subData.get("spAmount").toString())){
						backMsgByRow += "采购数量必须为正整数；";
					}
				}

				if(checkUtil.isNotNullByObject(subData.get("subTotalAmount"))){//子件总数不为空时，必须是整数
					if(!checkUtil.isZeroOrPositiveInt(subData.get("subTotalAmount").toString())){
						backMsgByRow += "子件总数必须为整数；";
					}
				}

				if(checkUtil.isNotNullByObject(backMsgByRow)){
					backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
				}


				if(checkUtil.isNotNullByObject(subData.get("subTotalPrice"))){
					subTotalPrice = subTotalPrice.add(new BigDecimal(subData.get("subTotalPrice").toString()));
				}
			}

			//负债判断
			if(checkUtil.isNotNullByObject(params.get("vgsbm"))){
				//获取公司编码
				String vGsBm = params.get("vgsbm").toString();
				//根据公司编码获取对应的实时资金表信息
				TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
				//获取对应的实时资金信息
				BigDecimal amountAble = account.getFJe().add(account.getFFzEd()).subtract(account.getFDjJe());
				//判断金额是否大于公司的实时资金
				if (amountAble.compareTo(subTotalPrice) < 0) {
					backMsg += "【" + vGsBm + "】账户可用余额不足，无法流转";
				}
			}

		}else{
			backMsg = "列表信息为空";
		}
		checkByGrid.setErrMsg(backMsg);
		checkByGrid.setSubDataList(subDataList);

		return checkByGrid;
	}



	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String,Object> extraParam = new TcgPurchaseByPlan()

				.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
				.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

				.addLeftJoin("THR_OperateCompanyApply D ON D.Vgsbm = A.Vgsbm ")//运营公司管理表
				.addField("D.Vgsjc AS vgsjc")//采购公司简称
				.addField("D.Vgsmc AS vgsmc")//采购公司名称
				.addField("D.VgsSh AS vgsSh")//税号

				.addLeftJoin("TCG_PurchaseAddress E ON E.Id = A.PurchaseAddressId ")//采购地址维护
				.addField("E.VGjH + ',' + E.VSfH + ',' + E.VDsH + ',' + E.VCqH + ',' + E.VDzH  AS addressDetail")//地址详情

				.addLeftJoin("(SELECT SUM((H.PurchaseAmount + H.JgSl) * H.Bprice) AS totalPrice,H.Pbid FROM TCG_PurchaseByPlanSon H GROUP BY H.Pbid) I ON I.Pbid = A.Bid")
				.addField("I.TotalPrice AS totalPrice")//采购预估金额

				.setBid(bid)
				.queryFirstMap();
		return extraParam;
	}


}
